package com.sasis.webapp.validator;

import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.Field;
import org.apache.commons.validator.Validator;
import org.apache.commons.validator.ValidatorAction;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.upload.FormFile;

public class FormFileCheck implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5945925581847609599L;

	private static Log log = LogFactory.getLog(FormFileCheck.class);

	private static final String VAR_MAX_SIZE = "maxFileSize";

	private static final String VAR_SUFFIXS = "suffixs";

	private static final String VALUE_SEP = ",";

	public FormFileCheck() {

	}

	public static boolean validateFileSuffix(Object bean, ValidatorAction va,
			Field field, ActionMessages errors, Validator validator,
			HttpServletRequest request) {

		Object value = getProperty(bean, field);

		if (value == null) {
			return true;
		}

		if (!(value instanceof FormFile)) {
			errors.add(field.getKey(), new ActionMessage("filecheck.invalid"));
			return false;
		}

		FormFile file = (FormFile) value;

		if (file.getFileName() == null || file.getFileName().equals("")) {
			return true;
		}

		log.info("file size :" + file.getFileSize());

		String suffixs = field.getVarValue(VAR_SUFFIXS);

		if ("".equals(suffixs.trim())) {
			return true;
		}

		String[] arrSuffixs = suffixs.split(VALUE_SEP);
		String fileName = file.getFileName();

		if (checkFileSuffix(fileName, arrSuffixs)) {
			return true;
		} else {
			errors.add(field.getKey(), new ActionMessage(
					"filecheck.type.invalid", suffixs));
			return false;
		}

	}

	public static boolean validateFileSize(Object bean, ValidatorAction va,
			Field field, ActionMessages errors, Validator validator,
			HttpServletRequest request) {

		Object value = getProperty(bean, field);

		if (value == null) {
			return true;
		}

		if (!(value instanceof FormFile)) {
			errors.add(field.getKey(), new ActionMessage("filecheck.invalid"));
			return false;
		}

		FormFile file = (FormFile) value;

		int size = file.getFileSize();

		if (size == 0)
			return true;

		int maxSize = 0;

		String sMaxSize = field.getVarValue(VAR_MAX_SIZE);
		if (sMaxSize != null && !sMaxSize.trim().equals("")) {
			maxSize = 1;
			String arrMaxSize[] = sMaxSize.split("[*]");
			for (int i = 0; i < arrMaxSize.length; i++) {
				if (!"".equals(arrMaxSize[i])) {
					log.info("part size :" + Integer.parseInt(arrMaxSize[i]));
					maxSize *= Integer.parseInt(arrMaxSize[i]);
				}
			}
		}

		log.info("max file size :" + maxSize);

		if (size <= maxSize) {
			return true;
		} else {

			int k = 1024;
			int m = 1024 * 1024;
			String param;
			if (maxSize / m > 0) {
				param = String.valueOf(maxSize / m) + "M";
			} else {
				param = String.valueOf(maxSize / k) + "K";
			}
			errors.add(field.getKey(), new ActionMessage(
					"filecheck.filetoolarge", param));
			return false;
		}
	}

	private static Object getProperty(Object bean, Field field) {

		Object value = null;

		try {
			value = PropertyUtils.getProperty(bean, field.getProperty());
		} catch (IllegalAccessException e) {
			log.error(e.getMessage(), e);
		} catch (InvocationTargetException e) {
			log.error(e.getMessage(), e);
		} catch (NoSuchMethodException e) {
			log.error(e.getMessage(), e);
		}
		return value;

	}

	private static boolean checkFileSuffix(String fileName, String[] arrSuffixs) {
		if (fileName == null || "".equals(fileName))
			return false;
		int index = fileName.lastIndexOf(".");
		if (index > (fileName.length() - 2))
			return false;
		String suffix = fileName.substring(index + 1, fileName.length());
		for (int i = 0; i < arrSuffixs.length; i++) {
			if (suffix.equalsIgnoreCase(arrSuffixs[i]))
				return true;
		}
		return false;
	}

}
